#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
火之夜工作室 Flutter 项目创建脚本

基于当前项目模板创建一个新的 Flutter 项目
使用方法: python3 create_project.py
"""

import os
import sys
from lib_copier import copy_lib_directory
from flutter_project_creator import run_flutter_create
import user_interaction

from utils import print_colored, update_readme



def main():
    """
    主函数
    """
    print_colored("\n火之夜工作室 Flutter 项目创建工具\n", "cyan")
    print_colored("该脚本将基于当前项目模板创建一个新的Flutter项目\n", "cyan")
    # 从user_interaction模块获取项目类型
    project_type = user_interaction.get_project_type()
    # 从user_interaction模块获取模板类型
    template_type = user_interaction.get_template_type()
    
    # 获取当前脚本所在目录作为源目录
    source_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 获取项目信息
    project_name, package_name, display_name, parent_dir, target_dir = user_interaction.get_project_info(source_dir, project_type)
    
    # 验证目标目录是否存在并具有写权限
    if not os.path.exists(parent_dir):
        try:
            os.makedirs(parent_dir)
        except OSError as e:
            print_colored(f"错误: 无法创建目录 {parent_dir}: {str(e)}", "red")
            return
    
    # 检查目标目录是否具有写权限
    if not os.access(parent_dir, os.W_OK):
        print_colored(f"错误: 目录 {parent_dir} 没有写权限", "red")
        return

    # 检查目标目录是否已存在
    if os.path.exists(target_dir) and not user_interaction.confirm_overwrite(target_dir):
        print_colored("操作已取消", "yellow")
        return
    
    import shutil
    if os.path.exists(target_dir):
        shutil.rmtree(target_dir)
    
    # 使用flutter create创建新项目
    if not run_flutter_create(target_dir, project_name, package_name, project_type):
        return
    
    # 复制项目文件
    template_branch = 'master' if template_type == '1' else 'depend-get'
    if not copy_lib_directory(source_dir, target_dir, project_name,project_type, package_name, display_name, branch=template_branch):
        return
    
    # 更新README.md
    update_readme(target_dir, project_name, display_name)

    # 打印完成信息
    print_colored(f"\n新项目已创建成功！", "green")
    print_colored(f"项目路径: {target_dir}", "green")
    print_colored(f"\n执行以下命令开始开发:\n", "blue")
    print_colored(f"cd {target_dir}", "yellow")
    print_colored(f"flutter pub get", "yellow")
    print_colored(f"flutter run", "yellow")
    
    # 获取用户选择的IDE类型
    ide_choice = user_interaction.get_ide_choice()
    
    # 自动打开项目
    from utils import open_project_in_ide
    open_project_in_ide(target_dir, ide_choice)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print_colored("\n操作已取消", "yellow")
        sys.exit(0)
    except Exception as e:
        print_colored(f"\n错误: {str(e)}", "red")
        sys.exit(1)